package com.banhujiu.spider.region.enties

import com.banhujiu.spider.region.conf.fileName
import com.banhujiu.spider.region.conf.filePath
import com.banhujiu.spider.region.conf.fileSuffix
import com.banhujiu.spider.region.conf.initString
import com.banhujiu.spider.region.exceptions.NoAbsolutePathException
import java.io.File
import java.io.FileWriter
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.locks.StampedLock

/**
 * @author banhujiu
 * @date 2017/11/25 0025 19:14
 */
class FileEntry {
    val readWriteLock: StampedLock = StampedLock()
    var file: File = File("")
    val count: AtomicInteger = AtomicInteger(0)

    constructor() {
        init(filePath, fileName, fileSuffix)
    }

    private fun init(filePath: String, filename: String, fileSuffix: String?) {
        var fileNameTemp: String = filePath + filename
        if (fileSuffix != null) {
            if (!fileNameTemp.endsWith(fileSuffix)) {
                fileNameTemp += fileSuffix
            }
        }
        file = File(fileNameTemp)
        if (!file.isAbsolute) {
            throw NoAbsolutePathException()
        }
        if (!file.exists()) {
            file.createNewFile()
        }
        val fw = FileWriter(file)
        fw.write(initString)
        fw.flush()
    }

}
